package com.app.dao;

import com.app.bean.UserDetail;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.ArrayList;
import java.util.List;
/**
 *
 * User: Murilo Dourado
 * Date: 07/12/11
 * Time: 21:29
 *
 */
public class UserDAO extends HibernateDaoSupport {

    private static Logger logger = Logger.getLogger(UserDAO.class);

    public void saveUser(UserDetail bean){
        try{
            getSession().save(bean);
        }catch (Exception ex){
            logger.error("Error saving or update a new user: ", ex);
        }
    }

    public List<UserDetail> selectUserByEmail(UserDetail bean){
        List<UserDetail> result = new ArrayList<UserDetail>();
        try{
            result = getSession().createCriteria(UserDetail.class)
                    .add(Restrictions.eq("userEmail", bean.getUserEmail()))
                    .list();
        }catch (Exception ex){
            logger.error("Error saving or update a new user: ", ex);
        }
        return result;
    }

    public String deleteUser(UserDetail bean){
        String result = "";
        try{
           getSession().delete(bean);
           result = bean.getUserName();
        } catch(Exception ex){
            logger.error("Error to delete a user: ", ex);
            result = "Error to delete a user: " + bean.getUserName();
        }
        return result;
    }

    public String updateUser(UserDetail bean){
        String result = "";
        try{
            getSession().saveOrUpdate(bean);
            result = bean.getUserName();
        }catch (Exception ex){
            logger.error("Error to execute a update user",ex);
            result = "User was not updated";
        }
        return result;
    }


}